package top.lixunda.common.validate.validate;

import top.lixunda.common.validate.exception.XumValidException;

/**
 * @author Xumda
 * @version time:2019/12/12 16:44
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public class ValidatorPrivateUtils {

    /**
     * 将Character, Short, Integer, Long 类型的对象转换为long
     *
     * @param value    Object
     * @param throwExe value为空以及类型错误时是否抛出异常，不抛出异常返回默认值0L
     * @return 转换后的long类型，当value为空或类型错误时返回0L
     * @throws XumValidException value为空或类型错误
     */
    public static long getLongFromNumber(Object value, boolean throwExe) {
        if (value == null && throwExe) {
            throw new XumValidException("转换参数不能为空");
        } else if (value == null) {
            return 0L;
        }
        long i;
        if (value instanceof Character) {
            i = (long) (char) value;
        } else if (value instanceof Short) {
            i = (long) (short) value;
        } else if (value instanceof Integer) {
            i = (long) (int) value;
        } else if (value instanceof Long) {
            i = (long) value;
        } else {
            if (throwExe) {
                throw new XumValidException("getLongFromNumber 函数仅支持 Character, Short, Integer, Long 类型, " +
                        "调用前请先验证或设置throwExe参数为false");
            } else {
                i = 0L;
            }
        }
        return i;
    }

    /**
     * 将Float, Double 类型的对象转换为Double
     *
     * @param value Object
     * @return 转换后的Double类型，当value为空或类型错误时返回0
     * @throws XumValidException value为空或类型错误
     */
    public static double getDoubleFromNumber(Object value) {
        return getDoubleFromNumber(value, true);
    }

    /**
     * 将Float, Double 类型的对象转换为Double
     *
     * @param value    Object
     * @param throwExe value为空以及类型错误时是否抛出异常，不抛出异常返回默认值0L
     * @return 转换后的Double类型，当value为空或类型错误时返回0
     * @throws XumValidException value为空或类型错误
     */
    public static double getDoubleFromNumber(Object value, boolean throwExe) {
        if (value == null && throwExe) {
            throw new XumValidException("转换参数不能为空");
        } else if (value == null) {
            return 0.0;
        }
        double i;
        if (value instanceof Float) {
            i = (double) (float) value;
        } else if (value instanceof Double) {
            i = (double) value;
        } else {
            if (throwExe) {
                throw new XumValidException("getDoubleFromNumber 函数仅支持 Float, Double 类型, " +
                        "调用前请先验证或设置throwExe参数为false");
            } else {
                i = 0.0;
            }
        }
        return i;
    }

    /**
     * 将Character, Short, Integer, Long 类型的对象转换为long
     *
     * @param value Object
     * @return 转换后的long类型，当value为空或类型错误时返回0L
     * @throws XumValidException value为空或类型错误
     */
    public static long getLongFromNumber(Object value) {
        return getLongFromNumber(value, true);
    }

}
